import { DesignPattern } from '@/types';

export const behavioralPatterns: DesignPattern[] = [
  // 行为模式 - 观察者
  {
    id: 'observer',
    name: '观察者模式',
    category: 'behavioral',
    difficulty: '中等',
    description: '观察者模式定义对象间的一种一对多的依赖关系，当一个对象的状态发生改变时，所有依赖于它的对象都得到通知并被自动更新。',
    principles: [
      '定义对象间一对多的依赖关系',
      '当主题状态改变时通知所有观察者',
      '支持广播通信',
      '松散耦合的设计'
    ],
    useCases: [
      '事件处理系统',
      'MVC架构',
      '发布-订阅系统',
      '数据绑定',
      '响应式编程'
    ],
    advantages: [
      '支持松散耦合',
      '支持广播通信',
      '符合开闭原则',
      '建立抽象耦合'
    ],
    disadvantages: [
      '可能引起循环依赖',
      '观察者过多时影响性能',
      '没有相应的机制让观察者知道所观察的目标对象是怎么发生变化的'
    ],
    code: `// 观察者模式示例
// 观察者接口
interface Observer {
  update(subject: Subject): void;
}

// 主题接口
interface Subject {
  attach(observer: Observer): void;
  detach(observer: Observer): void;
  notify(): void;
}

// 具体主题
class ConcreteSubject implements Subject {
  private observers: Observer[] = [];
  private state: number = 0;
  
  attach(observer: Observer): void {
    const isExist = this.observers.includes(observer);
    if (isExist) {
      console.log('Observer has been attached already.');
      return;
    }
    
    console.log('Attached an observer.');
    this.observers.push(observer);
  }
  
  detach(observer: Observer): void {
    const observerIndex = this.observers.indexOf(observer);
    if (observerIndex === -1) {
      console.log('Nonexistent observer.');
      return;
    }
    
    this.observers.splice(observerIndex, 1);
    console.log('Detached an observer.');
  }
  
  notify(): void {
    console.log('Notifying observers...');
    for (const observer of this.observers) {
      observer.update(this);
    }
  }
  
  someBusinessLogic(): void {
    console.log('\\nSubject: I\\'m doing something important.');
    this.state = Math.floor(Math.random() * (10 + 1));
    
    console.log(\`Subject: My state has just changed to: \${this.state}\`);
    this.notify();
  }
  
  getState(): number {
    return this.state;
  }
}

// 具体观察者
class ConcreteObserverA implements Observer {
  update(subject: Subject): void {
    if (subject instanceof ConcreteSubject && subject.getState() < 3) {
      console.log('ConcreteObserverA: Reacted to the event.');
    }
  }
}

class ConcreteObserverB implements Observer {
  update(subject: Subject): void {
    if (subject instanceof ConcreteSubject && (subject.getState() === 0 || subject.getState() >= 2)) {
      console.log('ConcreteObserverB: Reacted to the event.');
    }
  }
}

// 使用示例
const subject = new ConcreteSubject();

const observer1 = new ConcreteObserverA();
subject.attach(observer1);

const observer2 = new ConcreteObserverB();
subject.attach(observer2);

subject.someBusinessLogic();
subject.someBusinessLogic();

subject.detach(observer2);

subject.someBusinessLogic();`,
    demoCode: `const subject = new ConcreteSubject();
const observer1 = new ConcreteObserverA();
const observer2 = new ConcreteObserverB();

subject.attach(observer1);
subject.attach(observer2);

subject.someBusinessLogic(); // 通知所有观察者`,
    realWorldExamples: [
      {
        title: '事件监听器',
        description: 'DOM事件的观察者模式实现',
        code: `class EventEmitter {
  private listeners: Map<string, Function[]> = new Map();
  
  on(event: string, callback: Function) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, []);
    }
    this.listeners.get(event)!.push(callback);
  }
  
  emit(event: string, data?: any) {
    const callbacks = this.listeners.get(event);
    if (callbacks) {
      callbacks.forEach(callback => callback(data));
    }
  }
}`
      },
      {
        title: 'Vue.js响应式系统',
        description: '数据变化自动更新视图',
        code: `class Reactive {
  private observers: Set<Function> = new Set();
  
  observe(fn: Function) {
    this.observers.add(fn);
  }
  
  notify() {
    this.observers.forEach(fn => fn());
  }
}`
      }
    ],
    bestPractices: [
      '使用事件委托',
      '避免循环依赖',
      '及时移除观察者',
      '考虑异步通知'
    ],
    icon: 'Eye'
  },

  // 行为模式 - 责任链
  {
    id: 'chain-of-responsibility',
    name: '责任链模式',
    category: 'behavioral',
    difficulty: '中等',
    description: '责任链模式为请求创建了一个接收者对象的链。这种模式给予请求的类型，对请求的发送者和接收者进行解耦。',
    principles: [
      '将请求的发送者和接收者解耦',
      '多个对象都有机会处理请求',
      '沿着链传递请求直到有对象处理',
      '动态组织和分配责任'
    ],
    useCases: [
      '审批流程',
      '异常处理',
      '日志记录',
      '权限验证',
      '事件处理'
    ],
    advantages: [
      '降低耦合度',
      '增强灵活性',
      '简化对象间连接',
      '动态添加或删除责任'
    ],
    disadvantages: [
      '性能受到影响',
      '调试困难',
      '可能导致循环调用'
    ],
    code: `// 责任链模式示例
// 抽象处理者
abstract class Handler {
  protected nextHandler: Handler | null = null;
  
  setNext(handler: Handler): Handler {
    this.nextHandler = handler;
    return handler;
  }
  
  handle(request: string): string | null {
    if (this.nextHandler) {
      return this.nextHandler.handle(request);
    }
    return null;
  }
}

// 具体处理者
class MonkeyHandler extends Handler {
  handle(request: string): string | null {
    if (request === 'Banana') {
      return \`Monkey: I'll eat the \${request}\`;
    }
    return super.handle(request);
  }
}

class SquirrelHandler extends Handler {
  handle(request: string): string | null {
    if (request === 'Nut') {
      return \`Squirrel: I'll eat the \${request}\`;
    }
    return super.handle(request);
  }
}

class DogHandler extends Handler {
  handle(request: string): string | null {
    if (request === 'MeatBall') {
      return \`Dog: I'll eat the \${request}\`;
    }
    return super.handle(request);
  }
}

// 使用示例
const monkey = new MonkeyHandler();
const squirrel = new SquirrelHandler();
const dog = new DogHandler();

monkey.setNext(squirrel).setNext(dog);

// 客户端代码
function clientCode(handler: Handler) {
  const foods = ['Nut', 'Banana', 'Coffee'];
  
  foods.forEach(food => {
    console.log(\`Client: Who wants a \${food}?\`);
    const result = handler.handle(food);
    if (result) {
      console.log(\`  \${result}\`);
    } else {
      console.log(\`  \${food} was left untouched.\`);
    }
  });
}

clientCode(monkey);`,
    demoCode: `const monkey = new MonkeyHandler();
const squirrel = new SquirrelHandler();
const dog = new DogHandler();

monkey.setNext(squirrel).setNext(dog);

console.log(monkey.handle('Banana')); // Monkey处理
console.log(monkey.handle('Nut'));    // Squirrel处理
console.log(monkey.handle('Coffee')); // 无人处理`,
    realWorldExamples: [
      {
        title: '审批流程',
        description: '多级审批系统',
        code: `class ApprovalHandler extends Handler {
  constructor(private level: number, private name: string) {
    super();
  }
  
  handle(amount: number): string | null {
    if (amount <= this.level) {
      return \`\${this.name} approved \${amount}\`;
    }
    return super.handle(amount);
  }
}`
      },
      {
        title: 'Express中间件',
        description: 'Web框架的中间件链',
        code: `class Middleware {
  constructor(private fn: Function) {}
  
  handle(req: any, res: any, next: Function) {
    this.fn(req, res, next);
  }
}`
      }
    ],
    bestPractices: [
      '确保链中至少有一个处理者',
      '避免过长的责任链',
      '考虑性能影响',
      '提供默认处理者'
    ],
    icon: 'Network'
  },

  // 行为模式 - 命令
  {
    id: 'command',
    name: '命令模式',
    category: 'behavioral',
    difficulty: '中等',
    description: '命令模式将请求封装成对象，从而使你可用不同的请求对客户进行参数化；对请求排队或者记录请求日志，以及支持撤销操作。',
    principles: [
      '将请求封装为对象',
      '分离调用者和接收者',
      '支持撤销和重做操作',
      '支持日志记录和事务'
    ],
    useCases: [
      '撤销/重做功能',
      '宏命令',
      '队列请求',
      '日志记录',
      '事务处理'
    ],
    advantages: [
      '降低系统耦合度',
      '容易扩展新命令',
      '支持撤销操作',
      '支持宏命令'
    ],
    disadvantages: [
      '增加系统复杂度',
      '可能产生大量命令类'
    ],
    code: `// 命令模式示例
// 命令接口
interface Command {
  execute(): void;
  undo(): void;
}

// 接收者
class Light {
  private isOn: boolean = false;
  
  turnOn(): void {
    this.isOn = true;
    console.log('Light is ON');
  }
  
  turnOff(): void {
    this.isOn = false;
    console.log('Light is OFF');
  }
  
  getState(): boolean {
    return this.isOn;
  }
}

// 具体命令
class LightOnCommand implements Command {
  constructor(private light: Light) {}
  
  execute(): void {
    this.light.turnOn();
  }
  
  undo(): void {
    this.light.turnOff();
  }
}

class LightOffCommand implements Command {
  constructor(private light: Light) {}
  
  execute(): void {
    this.light.turnOff();
  }
  
  undo(): void {
    this.light.turnOn();
  }
}

// 空命令（空对象模式）
class NoCommand implements Command {
  execute(): void {}
  undo(): void {}
}

// 调用者
class RemoteControl {
  private commands: Command[] = [];
  private undoCommand: Command = new NoCommand();
  
  setCommand(slot: number, command: Command): void {
    this.commands[slot] = command;
  }
  
  pressButton(slot: number): void {
    if (this.commands[slot]) {
      this.commands[slot].execute();
      this.undoCommand = this.commands[slot];
    }
  }
  
  pressUndo(): void {
    this.undoCommand.undo();
  }
}

// 宏命令
class MacroCommand implements Command {
  constructor(private commands: Command[]) {}
  
  execute(): void {
    this.commands.forEach(command => command.execute());
  }
  
  undo(): void {
    // 逆序撤销
    for (let i = this.commands.length - 1; i >= 0; i--) {
      this.commands[i].undo();
    }
  }
}

// 使用示例
const light = new Light();
const lightOn = new LightOnCommand(light);
const lightOff = new LightOffCommand(light);

const remote = new RemoteControl();
remote.setCommand(0, lightOn);
remote.setCommand(1, lightOff);

remote.pressButton(0); // Light is ON
remote.pressButton(1); // Light is OFF
remote.pressUndo();    // Light is ON

// 宏命令示例
const macroOn = new MacroCommand([lightOn]);
const macroOff = new MacroCommand([lightOff]);

remote.setCommand(2, macroOn);
remote.pressButton(2); // 执行宏命令`,
    demoCode: `const light = new Light();
const lightOn = new LightOnCommand(light);
const remote = new RemoteControl();

remote.setCommand(0, lightOn);
remote.pressButton(0); // 执行命令
remote.pressUndo();    // 撤销命令`,
    realWorldExamples: [
      {
        title: '文本编辑器',
        description: '撤销/重做功能',
        code: `class TextEditor {
  private history: Command[] = [];
  private currentPosition = -1;
  
  executeCommand(command: Command) {
    command.execute();
    this.history = this.history.slice(0, this.currentPosition + 1);
    this.history.push(command);
    this.currentPosition++;
  }
  
  undo() {
    if (this.currentPosition >= 0) {
      this.history[this.currentPosition].undo();
      this.currentPosition--;
    }
  }
}`
      },
      {
        title: '任务队列',
        description: '异步任务处理',
        code: `class TaskQueue {
  private queue: Command[] = [];
  
  addTask(command: Command) {
    this.queue.push(command);
  }
  
  processTasks() {
    while (this.queue.length > 0) {
      const task = this.queue.shift();
      task?.execute();
    }
  }
}`
      }
    ],
    bestPractices: [
      '合理设计命令接口',
      '考虑命令的生命周期',
      '实现撤销功能时注意状态管理',
      '使用宏命令组合复杂操作'
    ],
    icon: 'Zap'
  },

  // 行为模式 - 迭代器
  {
    id: 'iterator',
    name: '迭代器模式',
    category: 'behavioral',
    difficulty: '简单',
    description: '迭代器模式提供一种方法顺序访问一个聚合对象中各个元素，而又不需暴露该对象的内部表示。',
    principles: [
      '提供统一的遍历接口',
      '隐藏集合的内部结构',
      '支持多种遍历方式',
      '分离集合和遍历算法'
    ],
    useCases: [
      '集合遍历',
      '数据结构访问',
      '树形结构遍历',
      '分页数据处理',
      '流式数据处理'
    ],
    advantages: [
      '简化聚合类接口',
      '支持多种遍历方式',
      '增加新的聚合类很方便',
      '封装性良好'
    ],
    disadvantages: [
      '增加系统复杂度',
      '对于简单遍历过度设计'
    ],
    code: `// 迭代器模式示例
// 迭代器接口
interface Iterator<T> {
  hasNext(): boolean;
  next(): T | null;
  current(): T | null;
}

// 聚合接口
interface Aggregator<T> {
  createIterator(): Iterator<T>;
}

// 具体迭代器
class BookIterator implements Iterator<string> {
  private position: number = 0;
  
  constructor(private books: BookCollection) {}
  
  hasNext(): boolean {
    return this.position < this.books.getLength();
  }
  
  next(): string | null {
    if (this.hasNext()) {
      const book = this.books.getBookAt(this.position);
      this.position++;
      return book;
    }
    return null;
  }
  
  current(): string | null {
    if (this.position > 0 && this.position <= this.books.getLength()) {
      return this.books.getBookAt(this.position - 1);
    }
    return null;
  }
}

// 反向迭代器
class ReverseBookIterator implements Iterator<string> {
  private position: number;
  
  constructor(private books: BookCollection) {
    this.position = books.getLength() - 1;
  }
  
  hasNext(): boolean {
    return this.position >= 0;
  }
  
  next(): string | null {
    if (this.hasNext()) {
      const book = this.books.getBookAt(this.position);
      this.position--;
      return book;
    }
    return null;
  }
  
  current(): string | null {
    if (this.position >= -1 && this.position < this.books.getLength() - 1) {
      return this.books.getBookAt(this.position + 1);
    }
    return null;
  }
}

// 具体聚合
class BookCollection implements Aggregator<string> {
  private books: string[] = [];
  
  addBook(book: string): void {
    this.books.push(book);
  }
  
  getBookAt(index: number): string {
    return this.books[index];
  }
  
  getLength(): number {
    return this.books.length;
  }
  
  createIterator(): Iterator<string> {
    return new BookIterator(this);
  }
  
  createReverseIterator(): Iterator<string> {
    return new ReverseBookIterator(this);
  }
}

// 使用示例
const bookCollection = new BookCollection();
bookCollection.addBook('Design Patterns');
bookCollection.addBook('Clean Code');
bookCollection.addBook('Refactoring');

console.log('正向遍历:');
const iterator = bookCollection.createIterator();
while (iterator.hasNext()) {
  console.log(iterator.next());
}

console.log('\\n反向遍历:');
const reverseIterator = bookCollection.createReverseIterator();
while (reverseIterator.hasNext()) {
  console.log(reverseIterator.next());
}

// ES6 迭代器实现
class ModernBookCollection implements Iterable<string> {
  private books: string[] = [];
  
  addBook(book: string): void {
    this.books.push(book);
  }
  
  *[Symbol.iterator](): Iterator<string> {
    for (const book of this.books) {
      yield book;
    }
  }
  
  *reverseIterator(): Iterator<string> {
    for (let i = this.books.length - 1; i >= 0; i--) {
      yield this.books[i];
    }
  }
}

// 现代用法
const modernCollection = new ModernBookCollection();
modernCollection.addBook('TypeScript Handbook');
modernCollection.addBook('JavaScript: The Good Parts');

// 使用 for...of
for (const book of modernCollection) {
  console.log(book);
}

// 使用自定义迭代器
for (const book of modernCollection.reverseIterator()) {
  console.log(book);
}`,
    demoCode: `const collection = new BookCollection();
collection.addBook('Design Patterns');
collection.addBook('Clean Code');

const iterator = collection.createIterator();
while (iterator.hasNext()) {
  console.log(iterator.next());
}`,
    realWorldExamples: [
      {
        title: 'JavaScript Array',
        description: '内置的迭代器实现',
        code: `const arr = [1, 2, 3];
const iterator = arr[Symbol.iterator]();

console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: undefined, done: true}`
      },
      {
        title: '树形结构遍历',
        description: '深度优先遍历迭代器',
        code: `class TreeIterator {
  private stack: TreeNode[] = [];
  
  constructor(root: TreeNode) {
    if (root) this.stack.push(root);
  }
  
  hasNext(): boolean {
    return this.stack.length > 0;
  }
  
  next(): TreeNode | null {
    if (!this.hasNext()) return null;
    
    const node = this.stack.pop()!;
    // 右子树先入栈，左子树后入栈
    if (node.right) this.stack.push(node.right);
    if (node.left) this.stack.push(node.left);
    
    return node;
  }
}`
      }
    ],
    bestPractices: [
      '使用ES6的Symbol.iterator',
      '考虑迭代器的生命周期',
      '支持多种遍历方式',
      '注意并发修改问题'
    ],
    icon: 'List'
  },

  // 行为模式 - 中介者
  {
    id: 'mediator',
    name: '中介者模式',
    category: 'behavioral',
    difficulty: '中等',
    description: '中介者模式定义了一系列对象之间的交互。中介者使各对象不需要显式地相互引用，从而使其耦合松散，而且可以独立地改变它们之间的交互。',
    principles: [
      '定义对象间的交互方式',
      '减少对象间的直接依赖',
      '集中控制交互逻辑',
      '促进松散耦合'
    ],
    useCases: [
      '对话框控件交互',
      '聊天室系统',
      '航空交通控制',
      '工作流系统',
      'MVC架构'
    ],
    advantages: [
      '减少类间依赖',
      '提高组件复用性',
      '集中控制逻辑',
      '符合迪米特法则'
    ],
    disadvantages: [
      '中介者可能变得复杂',
      '可能成为性能瓶颈'
    ],
    code: `// 中介者模式示例
// 中介者接口
interface Mediator {
  notify(sender: Component, event: string): void;
}

// 抽象组件
abstract class Component {
  protected mediator: Mediator;
  
  constructor(mediator: Mediator) {
    this.mediator = mediator;
  }
  
  setMediator(mediator: Mediator): void {
    this.mediator = mediator;
  }
}

// 具体组件
class Button extends Component {
  click(): void {
    console.log('Button clicked');
    this.mediator.notify(this, 'click');
  }
}

class Textbox extends Component {
  private text: string = '';
  
  setText(text: string): void {
    this.text = text;
    console.log(\`Textbox text changed to: \${text}\`);
    this.mediator.notify(this, 'textChanged');
  }
  
  getText(): string {
    return this.text;
  }
}

class Checkbox extends Component {
  private checked: boolean = false;
  
  check(): void {
    this.checked = !this.checked;
    console.log(\`Checkbox \${this.checked ? 'checked' : 'unchecked'}\`);
    this.mediator.notify(this, 'check');
  }
  
  isChecked(): boolean {
    return this.checked;
  }
}

// 具体中介者
class DialogMediator implements Mediator {
  private button: Button;
  private textbox: Textbox;
  private checkbox: Checkbox;
  
  constructor() {
    this.button = new Button(this);
    this.textbox = new Textbox(this);
    this.checkbox = new Checkbox(this);
  }
  
  notify(sender: Component, event: string): void {
    if (sender === this.button && event === 'click') {
      console.log('Mediator reacts on button click');
      if (this.checkbox.isChecked()) {
        console.log(\`Processing: \${this.textbox.getText()}\`);
      } else {
        console.log('Checkbox must be checked first');
      }
    }
    
    if (sender === this.textbox && event === 'textChanged') {
      console.log('Mediator reacts on text change');
      // 可以启用/禁用按钮等
    }
    
    if (sender === this.checkbox && event === 'check') {
      console.log('Mediator reacts on checkbox change');
      // 可以根据复选框状态改变其他组件
    }
  }
  
  getButton(): Button { return this.button; }
  getTextbox(): Textbox { return this.textbox; }
  getCheckbox(): Checkbox { return this.checkbox; }
}

// 使用示例
const dialog = new DialogMediator();

dialog.getTextbox().setText('Hello World');
dialog.getCheckbox().check();
dialog.getButton().click();`,
    demoCode: `const dialog = new DialogMediator();

dialog.getTextbox().setText('Hello World');
dialog.getCheckbox().check();
dialog.getButton().click(); // 中介者协调各组件交互`,
    realWorldExamples: [
      {
        title: '聊天室',
        description: '用户通过聊天室中介者通信',
        code: `class ChatRoom {
  private users: User[] = [];
  
  addUser(user: User) {
    this.users.push(user);
  }
  
  sendMessage(message: string, from: User, to?: User) {
    if (to) {
      to.receive(message, from);
    } else {
      this.users.forEach(user => {
        if (user !== from) {
          user.receive(message, from);
        }
      });
    }
  }
}`
      },
      {
        title: 'MVC架构',
        description: 'Controller作为View和Model的中介者',
        code: `class Controller {
  constructor(private model: Model, private view: View) {
    view.setController(this);
  }
  
  handleUserAction(action: string, data: any) {
    this.model.update(data);
    this.view.render(this.model.getData());
  }
}`
      }
    ],
    bestPractices: [
      '避免中介者过于复杂',
      '合理划分中介者职责',
      '考虑使用观察者模式配合',
      '注意中介者的生命周期'
    ],
    icon: 'Network'
  },

  // 行为模式 - 备忘录
  {
    id: 'memento',
    name: '备忘录模式',
    category: 'behavioral',
    difficulty: '中等',
    description: '备忘录模式在不破坏封装性的前提下，捕获一个对象的内部状态，并在该对象之外保存这个状态，以便以后当需要时能将该对象恢复到原先保存的状态。',
    principles: [
      '保存对象的内部状态',
      '不破坏对象封装性',
      '提供状态恢复机制',
      '分离状态存储和业务逻辑'
    ],
    useCases: [
      '撤销操作',
      '事务回滚',
      '游戏存档',
      '编辑器历史',
      '系统快照'
    ],
    advantages: [
      '提供恢复机制',
      '保持封装边界',
      '简化发起人类',
      '支持多重备份'
    ],
    disadvantages: [
      '消耗内存资源',
      '管理备忘录的开销',
      '可能影响性能'
    ],
    code: `// 备忘录模式示例
// 备忘录类
class EditorMemento {
  private content: string;
  private cursorPosition: number;
  private selectionStart: number;
  private selectionEnd: number;
  
  constructor(
    content: string,
    cursorPosition: number,
    selectionStart: number,
    selectionEnd: number
  ) {
    this.content = content;
    this.cursorPosition = cursorPosition;
    this.selectionStart = selectionStart;
    this.selectionEnd = selectionEnd;
  }
  
  getContent(): string { return this.content; }
  getCursorPosition(): number { return this.cursorPosition; }
  getSelectionStart(): number { return this.selectionStart; }
  getSelectionEnd(): number { return this.selectionEnd; }
}

// 发起人类
class TextEditor {
  private content: string = '';
  private cursorPosition: number = 0;
  private selectionStart: number = 0;
  private selectionEnd: number = 0;
  
  write(text: string): void {
    this.content += text;
    this.cursorPosition = this.content.length;
    console.log(\`Content: "\${this.content}"\`);
  }
  
  delete(length: number): void {
    this.content = this.content.slice(0, -length);
    this.cursorPosition = this.content.length;
    console.log(\`Content: "\${this.content}"\`);
  }
  
  setCursor(position: number): void {
    this.cursorPosition = Math.max(0, Math.min(position, this.content.length));
  }
  
  select(start: number, end: number): void {
    this.selectionStart = Math.max(0, Math.min(start, this.content.length));
    this.selectionEnd = Math.max(0, Math.min(end, this.content.length));
  }
  
  // 创建备忘录
  save(): EditorMemento {
    return new EditorMemento(
      this.content,
      this.cursorPosition,
      this.selectionStart,
      this.selectionEnd
    );
  }
  
  // 恢复状态
  restore(memento: EditorMemento): void {
    this.content = memento.getContent();
    this.cursorPosition = memento.getCursorPosition();
    this.selectionStart = memento.getSelectionStart();
    this.selectionEnd = memento.getSelectionEnd();
    console.log(\`Restored content: "\${this.content}"\`);
  }
  
  getContent(): string {
    return this.content;
  }
}

// 管理者类
class EditorHistory {
  private mementos: EditorMemento[] = [];
  private currentIndex: number = -1;
  
  backup(editor: TextEditor): void {
    // 删除当前位置之后的所有备忘录
    this.mementos = this.mementos.slice(0, this.currentIndex + 1);
    
    // 添加新的备忘录
    this.mementos.push(editor.save());
    this.currentIndex++;
    
    console.log(\`Backup created. History size: \${this.mementos.length}\`);
  }
  
  undo(editor: TextEditor): boolean {
    if (this.currentIndex > 0) {
      this.currentIndex--;
      editor.restore(this.mementos[this.currentIndex]);
      console.log('Undo successful');
      return true;
    }
    console.log('Nothing to undo');
    return false;
  }
  
  redo(editor: TextEditor): boolean {
    if (this.currentIndex < this.mementos.length - 1) {
      this.currentIndex++;
      editor.restore(this.mementos[this.currentIndex]);
      console.log('Redo successful');
      return true;
    }
    console.log('Nothing to redo');
    return false;
  }
  
  showHistory(): void {
    console.log('History:');
    this.mementos.forEach((memento, index) => {
      const marker = index === this.currentIndex ? ' <-- current' : '';
      console.log(\`  \${index}: "\${memento.getContent()}"\${marker}\`);
    });
  }
}

// 使用示例
const editor = new TextEditor();
const history = new EditorHistory();

// 初始备份
history.backup(editor);

editor.write('Hello');
history.backup(editor);

editor.write(' World');
history.backup(editor);

editor.write('!');
history.backup(editor);

history.showHistory();

// 撤销操作
history.undo(editor);
history.undo(editor);

history.showHistory();

// 重做操作
history.redo(editor);

history.showHistory();`,
    demoCode: `const editor = new TextEditor();
const history = new EditorHistory();

history.backup(editor);
editor.write('Hello World');
history.backup(editor);

history.undo(editor); // 恢复到之前状态
history.redo(editor); // 重做操作`,
    realWorldExamples: [
      {
        title: '游戏存档',
        description: '保存和加载游戏状态',
        code: `class GameState {
  constructor(
    private level: number,
    private score: number,
    private playerPosition: {x: number, y: number}
  ) {}
  
  // getter methods...
}

class Game {
  save(): GameState {
    return new GameState(this.level, this.score, this.playerPosition);
  }
  
  load(state: GameState): void {
    // 恢复游戏状态
  }
}`
      },
      {
        title: '数据库事务',
        description: '事务回滚机制',
        code: `class DatabaseTransaction {
  private snapshots: Map<string, any> = new Map();
  
  begin() {
    // 创建数据快照
  }
  
  rollback() {
    // 恢复到事务开始时的状态
  }
}`
      }
    ],
    bestPractices: [
      '限制备忘录的数量',
      '考虑使用增量备份',
      '注意内存使用情况',
      '提供清理机制'
    ],
    icon: 'Archive'
  },

  // 行为模式 - 状态
  {
    id: 'state',
    name: '状态模式',
    category: 'behavioral',
    difficulty: '中等',
    description: '状态模式允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。',
    principles: [
      '将状态相关行为封装到状态类中',
      '消除复杂的条件语句',
      '状态转换更加明确',
      '支持状态的扩展'
    ],
    useCases: [
      '状态机',
      '游戏角色状态',
      '订单状态管理',
      '网络连接状态',
      'UI组件状态'
    ],
    advantages: [
      '消除复杂的条件分支',
      '状态转换更清晰',
      '易于扩展新状态',
      '符合开闭原则'
    ],
    disadvantages: [
      '增加类的数量',
      '状态间转换复杂时难以维护'
    ],
    code: `// 状态模式示例
// 状态接口
interface State {
  insertCoin(context: VendingMachine): void;
  selectProduct(context: VendingMachine): void;
  dispense(context: VendingMachine): void;
  refund(context: VendingMachine): void;
}

// 上下文类
class VendingMachine {
  private state: State;
  private coinInserted: boolean = false;
  private productSelected: boolean = false;
  
  constructor() {
    this.state = new IdleState();
  }
  
  setState(state: State): void {
    this.state = state;
    console.log(\`State changed to: \${state.constructor.name}\`);
  }
  
  insertCoin(): void {
    this.state.insertCoin(this);
  }
  
  selectProduct(): void {
    this.state.selectProduct(this);
  }
  
  dispense(): void {
    this.state.dispense(this);
  }
  
  refund(): void {
    this.state.refund(this);
  }
  
  setCoinInserted(inserted: boolean): void {
    this.coinInserted = inserted;
  }
  
  setProductSelected(selected: boolean): void {
    this.productSelected = selected;
  }
  
  isCoinInserted(): boolean {
    return this.coinInserted;
  }
  
  isProductSelected(): boolean {
    return this.productSelected;
  }
}

// 具体状态类
class IdleState implements State {
  insertCoin(context: VendingMachine): void {
    console.log('Coin inserted');
    context.setCoinInserted(true);
    context.setState(new HasCoinState());
  }
  
  selectProduct(context: VendingMachine): void {
    console.log('Please insert coin first');
  }
  
  dispense(context: VendingMachine): void {
    console.log('Please insert coin and select product first');
  }
  
  refund(context: VendingMachine): void {
    console.log('No coin to refund');
  }
}

class HasCoinState implements State {
  insertCoin(context: VendingMachine): void {
    console.log('Coin already inserted');
  }
  
  selectProduct(context: VendingMachine): void {
    console.log('Product selected');
    context.setProductSelected(true);
    context.setState(new ProductSelectedState());
  }
  
  dispense(context: VendingMachine): void {
    console.log('Please select a product first');
  }
  
  refund(context: VendingMachine): void {
    console.log('Coin refunded');
    context.setCoinInserted(false);
    context.setState(new IdleState());
  }
}

class ProductSelectedState implements State {
  insertCoin(context: VendingMachine): void {
    console.log('Coin already inserted');
  }
  
  selectProduct(context: VendingMachine): void {
    console.log('Product already selected');
  }
  
  dispense(context: VendingMachine): void {
    console.log('Dispensing product...');
    context.setCoinInserted(false);
    context.setProductSelected(false);
    context.setState(new DispensingState());
  }
  
  refund(context: VendingMachine): void {
    console.log('Coin refunded, product selection cancelled');
    context.setCoinInserted(false);
    context.setProductSelected(false);
    context.setState(new IdleState());
  }
}

class DispensingState implements State {
  insertCoin(context: VendingMachine): void {
    console.log('Please wait, dispensing product');
  }
  
  selectProduct(context: VendingMachine): void {
    console.log('Please wait, dispensing product');
  }
  
  dispense(context: VendingMachine): void {
    console.log('Product dispensed successfully');
    context.setState(new IdleState());
  }
  
  refund(context: VendingMachine): void {
    console.log('Cannot refund while dispensing');
  }
}

// 使用示例
const vendingMachine = new VendingMachine();

vendingMachine.selectProduct(); // Please insert coin first
vendingMachine.insertCoin();    // Coin inserted
vendingMachine.selectProduct(); // Product selected
vendingMachine.dispense();      // Dispensing product...
vendingMachine.dispense();      // Product dispensed successfully

console.log('\\n--- Another transaction ---');
vendingMachine.insertCoin();    // Coin inserted
vendingMachine.refund();        // Coin refunded`,
    demoCode: `const vendingMachine = new VendingMachine();

vendingMachine.insertCoin();    // 投币
vendingMachine.selectProduct(); // 选择商品
vendingMachine.dispense();      // 出货`,
    realWorldExamples: [
      {
        title: 'TCP连接状态',
        description: '网络连接的状态管理',
        code: `class TCPConnection {
  private state: ConnectionState;
  
  constructor() {
    this.state = new ClosedState();
  }
  
  open() { this.state.open(this); }
  close() { this.state.close(this); }
  acknowledge() { this.state.acknowledge(this); }
}`
      },
      {
        title: '音乐播放器',
        description: '播放器状态管理',
        code: `class MusicPlayer {
  private state: PlayerState;
  
  play() { this.state.play(this); }
  pause() { this.state.pause(this); }
  stop() { this.state.stop(this); }
}`
      }
    ],
    bestPractices: [
      '明确定义状态转换规则',
      '避免状态爆炸',
      '考虑使用状态图设计',
      '处理非法状态转换'
    ],
    icon: 'ToggleLeft'
  },

  // 行为模式 - 策略
  {
    id: 'strategy',
    name: '策略模式',
    category: 'behavioral',
    difficulty: '简单',
    description: '策略模式定义了一系列算法，把它们一个个封装起来，并且使它们可相互替换。策略模式让算法独立于使用它的客户而变化。',
    principles: [
      '定义算法家族并封装',
      '算法可以相互替换',
      '算法独立于客户端',
      '运行时选择算法'
    ],
    useCases: [
      '支付方式选择',
      '排序算法切换',
      '压缩算法选择',
      '验证规则',
      '价格计算策略'
    ],
    advantages: [
      '算法可以自由切换',
      '避免使用多重条件判断',
      '扩展性良好',
      '符合开闭原则'
    ],
    disadvantages: [
      '策略类数量增多',
      '客户端必须知道所有策略',
      '增加系统复杂度'
    ],
    code: `// 策略模式示例
// 策略接口
interface PaymentStrategy {
  pay(amount: number): void;
}

// 具体策略 - 信用卡支付
class CreditCardPayment implements PaymentStrategy {
  private cardNumber: string;
  private name: string;
  
  constructor(cardNumber: string, name: string) {
    this.cardNumber = cardNumber;
    this.name = name;
  }
  
  pay(amount: number): void {
    console.log(\`Paid \${amount} using Credit Card ending in \${this.cardNumber.slice(-4)}\`);
    console.log(\`Cardholder: \${this.name}\`);
  }
}

// 具体策略 - PayPal支付
class PayPalPayment implements PaymentStrategy {
  private email: string;
  
  constructor(email: string) {
    this.email = email;
  }
  
  pay(amount: number): void {
    console.log(\`Paid \${amount} using PayPal account: \${this.email}\`);
  }
}

// 具体策略 - 银行转账
class BankTransferPayment implements PaymentStrategy {
  private accountNumber: string;
  private bankName: string;
  
  constructor(accountNumber: string, bankName: string) {
    this.accountNumber = accountNumber;
    this.bankName = bankName;
  }
  
  pay(amount: number): void {
    console.log(\`Paid \${amount} via bank transfer to \${this.bankName}\`);
    console.log(\`Account: \${this.accountNumber}\`);
  }
}

// 上下文类
class ShoppingCart {
  private items: { name: string; price: number }[] = [];
  private paymentStrategy: PaymentStrategy | null = null;
  
  addItem(name: string, price: number): void {
    this.items.push({ name, price });
    console.log(\`Added \${name} (\${price}) to cart\`);
  }
  
  removeItem(name: string): void {
    const index = this.items.findIndex(item => item.name === name);
    if (index > -1) {
      this.items.splice(index, 1);
      console.log(\`Removed \${name} from cart\`);
    }
  }
  
  setPaymentStrategy(strategy: PaymentStrategy): void {
    this.paymentStrategy = strategy;
  }
  
  calculateTotal(): number {
    return this.items.reduce((total, item) => total + item.price, 0);
  }
  
  checkout(): void {
    if (!this.paymentStrategy) {
      console.log('Please select a payment method');
      return;
    }
    
    const total = this.calculateTotal();
    console.log(\`\\nCheckout Summary:\`);
    this.items.forEach(item => {
      console.log(\`- \${item.name}: $\${item.price}\`);
    });
    console.log(\`Total: $\${total}\\n\`);
    
    this.paymentStrategy.pay(total);
    this.items = []; // Clear cart after payment
  }
}

// 排序策略示例
interface SortStrategy {
  sort(data: number[]): number[];
}

class BubbleSort implements SortStrategy {
  sort(data: number[]): number[] {
    const arr = [...data];
    const n = arr.length;
    
    for (let i = 0; i < n - 1; i++) {
      for (let j = 0; j < n - i - 1; j++) {
        if (arr[j] > arr[j + 1]) {
          [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        }
      }
    }
    
    console.log('Sorted using Bubble Sort');
    return arr;
  }
}

class QuickSort implements SortStrategy {
  sort(data: number[]): number[] {
    const arr = [...data];
    this.quickSort(arr, 0, arr.length - 1);
    console.log('Sorted using Quick Sort');
    return arr;
  }
  
  private quickSort(arr: number[], low: number, high: number): void {
    if (low < high) {
      const pi = this.partition(arr, low, high);
      this.quickSort(arr, low, pi - 1);
      this.quickSort(arr, pi + 1, high);
    }
  }
  
  private partition(arr: number[], low: number, high: number): number {
    const pivot = arr[high];
    let i = low - 1;
    
    for (let j = low; j < high; j++) {
      if (arr[j] < pivot) {
        i++;
        [arr[i], arr[j]] = [arr[j], arr[i]];
      }
    }
    
    [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
    return i + 1;
  }
}

class SortContext {
  private strategy: SortStrategy;
  
  constructor(strategy: SortStrategy) {
    this.strategy = strategy;
  }
  
  setStrategy(strategy: SortStrategy): void {
    this.strategy = strategy;
  }
  
  executeSort(data: number[]): number[] {
    return this.strategy.sort(data);
  }
}

// 使用示例
console.log('=== Payment Strategy Example ===');
const cart = new ShoppingCart();

cart.addItem('Laptop', 999);
cart.addItem('Mouse', 25);
cart.addItem('Keyboard', 75);

// 使用信用卡支付
cart.setPaymentStrategy(new CreditCardPayment('1234567890123456', 'John Doe'));
cart.checkout();

// 重新添加商品并使用PayPal支付
cart.addItem('Monitor', 299);
cart.setPaymentStrategy(new PayPalPayment('john.doe@email.com'));
cart.checkout();

console.log('\\n=== Sorting Strategy Example ===');
const data = [64, 34, 25, 12, 22, 11, 90];
console.log(\`Original data: [\${data.join(', ')}]\`);

const sortContext = new SortContext(new BubbleSort());
let result = sortContext.executeSort(data);
console.log(\`Result: [\${result.join(', ')}]\`);

sortContext.setStrategy(new QuickSort());
result = sortContext.executeSort(data);
console.log(\`Result: [\${result.join(', ')}]\`);`,
    demoCode: `const cart = new ShoppingCart();
cart.addItem('Laptop', 999);

// 选择支付策略
cart.setPaymentStrategy(new CreditCardPayment('1234567890123456', 'John Doe'));
cart.checkout();`,
    realWorldExamples: [
      {
        title: '电商折扣策略',
        description: '不同类型用户的折扣计算',
        code: `interface DiscountStrategy {
  calculateDiscount(amount: number): number;
}

class RegularCustomerDiscount implements DiscountStrategy {
  calculateDiscount(amount: number): number {
    return amount * 0.05; // 5% discount
  }
}

class VIPCustomerDiscount implements DiscountStrategy {
  calculateDiscount(amount: number): number {
    return amount * 0.15; // 15% discount
  }
}

class PremiumCustomerDiscount implements DiscountStrategy {
  calculateDiscount(amount: number): number {
    return amount * 0.25; // 25% discount
  }
}`
      },
      {
        title: '文件压缩策略',
        description: '不同的压缩算法选择',
        code: `interface CompressionStrategy {
  compress(data: string): string;
}

class ZipCompression implements CompressionStrategy {
  compress(data: string): string {
    return \`ZIP[\${data}]\`;
  }
}

class RarCompression implements CompressionStrategy {
  compress(data: string): string {
    return \`RAR[\${data}]\`;
  }
}`
      }
    ],
    bestPractices: [
      '保持策略接口简洁',
      '使用工厂模式创建策略',
      '考虑策略的性能差异',
      '提供默认策略'
    ],
    icon: 'Target'
  },

  // 行为模式 - 模板方法
  {
    id: 'template-method',
    name: '模板方法模式',
    category: 'behavioral',
    difficulty: '简单',
    description: '模板方法模式在一个方法中定义一个算法的骨架，而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下，重新定义算法中的某些步骤。',
    principles: [
      '定义算法骨架',
      '延迟部分步骤到子类',
      '控制子类扩展',
      '代码复用'
    ],
    useCases: [
      '数据处理流程',
      '测试框架',
      '游戏AI行为',
      '文档生成',
      '工作流引擎'
    ],
    advantages: [
      '提高代码复用性',
      '控制子类扩展点',
      '符合开闭原则',
      '消除重复代码'
    ],
    disadvantages: [
      '增加系统复杂度',
      '子类数量可能增多',
      '违反里氏替换原则的风险'
    ],
    code: `// 模板方法模式示例
// 抽象类定义模板方法
abstract class DataProcessor {
  // 模板方法 - 定义算法骨架
  public processData(): void {
    console.log('Starting data processing...');
    
    const data = this.readData();
    const processedData = this.process(data);
    const validatedData = this.validate(processedData);
    this.saveData(validatedData);
    
    console.log('Data processing completed.');
  }
  
  // 抽象方法 - 子类必须实现
  protected abstract readData(): string[];
  protected abstract process(data: string[]): string[];
  protected abstract saveData(data: string[]): void;
  
  // 钩子方法 - 子类可以选择性重写
  protected validate(data: string[]): string[] {
    console.log('Performing default validation...');
    return data.filter(item => item && item.trim().length > 0);
  }
  
  // 具体方法 - 子类不能重写
  private logProgress(step: string): void {
    console.log(\`Progress: \${step}\`);
  }
}

// 具体子类 - CSV处理器
class CSVProcessor extends DataProcessor {
  protected readData(): string[] {
    console.log('Reading CSV file...');
    // 模拟从CSV文件读取数据
    return ['name,age,city', 'John,25,NYC', 'Jane,30,LA', '', 'Bob,35,Chicago'];
  }
  
  protected process(data: string[]): string[] {
    console.log('Processing CSV data...');
    return data.map(row => {
      if (row.includes(',')) {
        const fields = row.split(',');
        return fields.map(field => field.trim().toUpperCase()).join('|');
      }
      return row;
    });
  }
  
  protected saveData(data: string[]): void {
    console.log('Saving processed CSV data...');
    data.forEach((row, index) => {
      console.log(\`Row \${index + 1}: \${row}\`);
    });
  }
  
  // 重写钩子方法
  protected validate(data: string[]): string[] {
    console.log('Performing CSV-specific validation...');
    return super.validate(data).filter(row => 
      row.includes('|') || row.includes(',')
    );
  }
}

// 具体子类 - JSON处理器
class JSONProcessor extends DataProcessor {
  protected readData(): string[] {
    console.log('Reading JSON file...');
    // 模拟从JSON文件读取数据
    return [
      '{"name": "John", "age": 25}',
      '{"name": "Jane", "age": 30}',
      'invalid json',
      '{"name": "Bob", "age": 35}'
    ];
  }
  
  protected process(data: string[]): string[] {
    console.log('Processing JSON data...');
    return data.map(jsonStr => {
      try {
        const obj = JSON.parse(jsonStr);
        return \`\${obj.name} is \${obj.age} years old\`;
      } catch (e) {
        return 'Invalid JSON';
      }
    });
  }
  
  protected saveData(data: string[]): void {
    console.log('Saving processed JSON data...');
    const result = {
      processedAt: new Date().toISOString(),
      records: data
    };
    console.log('Saved:', JSON.stringify(result, null, 2));
  }
  
  // 重写钩子方法
  protected validate(data: string[]): string[] {
    console.log('Performing JSON-specific validation...');
    return super.validate(data).filter(item => 
      item !== 'Invalid JSON'
    );
  }
}

// 游戏AI模板方法示例
abstract class GameAI {
  // 模板方法
  public takeTurn(): void {
    this.collectResources();
    this.buildStructures();
    this.buildUnits();
    this.sendScouts();
    this.sendWarriors();
  }
  
  protected collectResources(): void {
    console.log('Collecting resources...');
  }
  
  // 抽象方法
  protected abstract buildStructures(): void;
  protected abstract buildUnits(): void;
  
  // 钩子方法
  protected sendScouts(): void {
    console.log('Sending scouts...');
  }
  
  protected sendWarriors(): void {
    console.log('Sending warriors...');
  }
}

class AggressiveAI extends GameAI {
  protected buildStructures(): void {
    console.log('Building barracks and weapon factories');
  }
  
  protected buildUnits(): void {
    console.log('Building lots of warriors');
  }
  
  protected sendScouts(): void {
    // 激进AI不派遣侦察兵
    console.log('Skipping scouts - going straight to attack!');
  }
}

class DefensiveAI extends GameAI {
  protected buildStructures(): void {
    console.log('Building walls and defensive towers');
  }
  
  protected buildUnits(): void {
    console.log('Building defensive units');
  }
  
  protected sendWarriors(): void {
    console.log('Keeping warriors for defense');
  }
}

// 使用示例
console.log('=== CSV Processing ===');
const csvProcessor = new CSVProcessor();
csvProcessor.processData();

console.log('\\n=== JSON Processing ===');
const jsonProcessor = new JSONProcessor();
jsonProcessor.processData();

console.log('\\n=== Game AI Examples ===');
console.log('Aggressive AI Turn:');
const aggressiveAI = new AggressiveAI();
aggressiveAI.takeTurn();

console.log('\\nDefensive AI Turn:');
const defensiveAI = new DefensiveAI();
defensiveAI.takeTurn();`,
    demoCode: `// 创建CSV处理器
const csvProcessor = new CSVProcessor();
csvProcessor.processData();

// 创建JSON处理器  
const jsonProcessor = new JSONProcessor();
jsonProcessor.processData();`,
    realWorldExamples: [
      {
        title: '单元测试框架',
        description: '测试用例的执行模板',
        code: `abstract class TestCase {
  public run(): void {
    this.setUp();
    try {
      this.runTest();
      this.recordSuccess();
    } catch (error) {
      this.recordFailure(error);
    } finally {
      this.tearDown();
    }
  }
  
  protected setUp(): void {}
  protected abstract runTest(): void;
  protected tearDown(): void {}
  
  private recordSuccess(): void {
    console.log('Test passed');
  }
  
  private recordFailure(error: any): void {
    console.log('Test failed:', error.message);
  }
}`
      },
      {
        title: 'HTTP请求处理',
        description: 'Web框架的请求处理模板',
        code: `abstract class RequestHandler {
  public handleRequest(request: any): any {
    if (!this.authenticate(request)) {
      return this.unauthorizedResponse();
    }
    
    const validatedData = this.validate(request);
    const result = this.process(validatedData);
    return this.formatResponse(result);
  }
  
  protected authenticate(request: any): boolean {
    return true; // Default implementation
  }
  
  protected abstract validate(request: any): any;
  protected abstract process(data: any): any;
  
  protected formatResponse(data: any): any {
    return { success: true, data };
  }
}`
      }
    ],
    bestPractices: [
      '明确区分抽象方法和钩子方法',
      '保持模板方法的稳定性',
      '合理使用钩子方法',
      '避免过深的继承层次'
    ],
    icon: 'FileText'
  },

  // 行为模式 - 访问者
  {
    id: 'visitor',
    name: '访问者模式',
    category: 'behavioral',
    difficulty: '困难',
    description: '访问者模式表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。',
    principles: [
      '分离算法与对象结构',
      '在不修改类的情况下增加新操作',
      '将相关操作集中到访问者中',
      '支持对象结构的遍历'
    ],
    useCases: [
      '编译器语法树处理',
      '文档结构处理',
      '图形对象操作',
      '数据结构遍历',
      '报表生成'
    ],
    advantages: [
      '增加新操作很容易',
      '相关操作集中在访问者中',
      '可以跨越类层次结构',
      '符合单一职责原则'
    ],
    disadvantages: [
      '增加新的元素类困难',
      '破坏封装性',
      '依赖具体类而非抽象'
    ],
    code: `// 访问者模式示例
// 访问者接口
interface Visitor {
  visitFile(file: File): void;
  visitDirectory(directory: Directory): void;
  visitSymlink(symlink: Symlink): void;
}

// 元素接口
interface FileSystemElement {
  accept(visitor: Visitor): void;
  getName(): string;
  getSize(): number;
}

// 具体元素 - 文件
class File implements FileSystemElement {
  private name: string;
  private size: number;
  private extension: string;
  
  constructor(name: string, size: number) {
    this.name = name;
    this.size = size;
    this.extension = name.split('.').pop() || '';
  }
  
  accept(visitor: Visitor): void {
    visitor.visitFile(this);
  }
  
  getName(): string {
    return this.name;
  }
  
  getSize(): number {
    return this.size;
  }
  
  getExtension(): string {
    return this.extension;
  }
}

// 具体元素 - 目录
class Directory implements FileSystemElement {
  private name: string;
  private children: FileSystemElement[] = [];
  
  constructor(name: string) {
    this.name = name;
  }
  
  accept(visitor: Visitor): void {
    visitor.visitDirectory(this);
  }
  
  getName(): string {
    return this.name;
  }
  
  getSize(): number {
    return this.children.reduce((total, child) => total + child.getSize(), 0);
  }
  
  addChild(child: FileSystemElement): void {
    this.children.push(child);
  }
  
  getChildren(): FileSystemElement[] {
    return this.children;
  }
}

// 具体元素 - 符号链接
class Symlink implements FileSystemElement {
  private name: string;
  private target: string;
  
  constructor(name: string, target: string) {
    this.name = name;
    this.target = target;
  }
  
  accept(visitor: Visitor): void {
    visitor.visitSymlink(this);
  }
  
  getName(): string {
    return this.name;
  }
  
  getSize(): number {
    return this.name.length; // 符号链接本身的大小
  }
  
  getTarget(): string {
    return this.target;
  }
}

// 具体访问者 - 大小计算器
class SizeCalculatorVisitor implements Visitor {
  private totalSize: number = 0;
  
  visitFile(file: File): void {
    this.totalSize += file.getSize();
    console.log(\`File: \${file.getName()} - \${file.getSize()} bytes\`);
  }
  
  visitDirectory(directory: Directory): void {
    console.log(\`Directory: \${directory.getName()}/\`);
    directory.getChildren().forEach(child => {
      child.accept(this);
    });
  }
  
  visitSymlink(symlink: Symlink): void {
    this.totalSize += symlink.getSize();
    console.log(\`Symlink: \${symlink.getName()} -> \${symlink.getTarget()}\`);
  }
  
  getTotalSize(): number {
    return this.totalSize;
  }
  
  reset(): void {
    this.totalSize = 0;
  }
}

// 具体访问者 - 文件类型统计
class FileTypeStatsVisitor implements Visitor {
  private stats: Map<string, { count: number; totalSize: number }> = new Map();
  
  visitFile(file: File): void {
    const extension = file.getExtension() || 'no-extension';
    const current = this.stats.get(extension) || { count: 0, totalSize: 0 };
    
    current.count++;
    current.totalSize += file.getSize();
    this.stats.set(extension, current);
  }
  
  visitDirectory(directory: Directory): void {
    directory.getChildren().forEach(child => {
      child.accept(this);
    });
  }
  
  visitSymlink(symlink: Symlink): void {
    // 符号链接不计入文件类型统计
  }
  
  getStats(): Map<string, { count: number; totalSize: number }> {
    return this.stats;
  }
  
  printStats(): void {
    console.log('\\nFile Type Statistics:');
    this.stats.forEach((stat, extension) => {
      console.log(\`.\${extension}: \${stat.count} files, \${stat.totalSize} bytes total\`);
    });
  }
}

// 具体访问者 - 搜索访问者
class SearchVisitor implements Visitor {
  private searchTerm: string;
  private results: FileSystemElement[] = [];
  
  constructor(searchTerm: string) {
    this.searchTerm = searchTerm.toLowerCase();
  }
  
  visitFile(file: File): void {
    if (file.getName().toLowerCase().includes(this.searchTerm)) {
      this.results.push(file);
    }
  }
  
  visitDirectory(directory: Directory): void {
    if (directory.getName().toLowerCase().includes(this.searchTerm)) {
      this.results.push(directory);
    }
    
    directory.getChildren().forEach(child => {
      child.accept(this);
    });
  }
  
  visitSymlink(symlink: Symlink): void {
    if (symlink.getName().toLowerCase().includes(this.searchTerm) ||
        symlink.getTarget().toLowerCase().includes(this.searchTerm)) {
      this.results.push(symlink);
    }
  }
  
  getResults(): FileSystemElement[] {
    return this.results;
  }
}

// 表达式访问者示例
interface Expression {
  accept(visitor: ExpressionVisitor): number;
}

interface ExpressionVisitor {
  visitNumber(number: NumberExpression): number;
  visitAddition(addition: AdditionExpression): number;
  visitMultiplication(multiplication: MultiplicationExpression): number;
}

class NumberExpression implements Expression {
  constructor(private value: number) {}
  
  accept(visitor: ExpressionVisitor): number {
    return visitor.visitNumber(this);
  }
  
  getValue(): number {
    return this.value;
  }
}

class AdditionExpression implements Expression {
  constructor(private left: Expression, private right: Expression) {}
  
  accept(visitor: ExpressionVisitor): number {
    return visitor.visitAddition(this);
  }
  
  getLeft(): Expression {
    return this.left;
  }
  
  getRight(): Expression {
    return this.right;
  }
}

class MultiplicationExpression implements Expression {
  constructor(private left: Expression, private right: Expression) {}
  
  accept(visitor: ExpressionVisitor): number {
    return visitor.visitMultiplication(this);
  }
  
  getLeft(): Expression {
    return this.left;
  }
  
  getRight(): Expression {
    return this.right;
  }
}

class EvaluatorVisitor implements ExpressionVisitor {
  visitNumber(number: NumberExpression): number {
    return number.getValue();
  }
  
  visitAddition(addition: AdditionExpression): number {
    return addition.getLeft().accept(this) + addition.getRight().accept(this);
  }
  
  visitMultiplication(multiplication: MultiplicationExpression): number {
    return multiplication.getLeft().accept(this) * multiplication.getRight().accept(this);
  }
}

// 使用示例
console.log('=== File System Visitor Example ===');

// 构建文件系统结构
const root = new Directory('root');
const documents = new Directory('Documents');
const pictures = new Directory('Pictures');

const resume = new File('resume.pdf', 1024);
const photo1 = new File('vacation.jpg', 2048);
const photo2 = new File('family.png', 1536);
const config = new File('config.json', 256);
const link = new Symlink('latest-photo', 'Pictures/vacation.jpg');

documents.addChild(resume);
documents.addChild(config);
pictures.addChild(photo1);
pictures.addChild(photo2);

root.addChild(documents);
root.addChild(pictures);
root.addChild(link);

// 使用大小计算访问者
const sizeVisitor = new SizeCalculatorVisitor();
root.accept(sizeVisitor);
console.log(\`\\nTotal size: \${sizeVisitor.getTotalSize()} bytes\`);

// 使用文件类型统计访问者
const statsVisitor = new FileTypeStatsVisitor();
root.accept(statsVisitor);
statsVisitor.printStats();

// 使用搜索访问者
const searchVisitor = new SearchVisitor('photo');
root.accept(searchVisitor);
console.log('\\nSearch results for "photo":');
searchVisitor.getResults().forEach(result => {
  console.log(\`- \${result.getName()}\`);
});

console.log('\\n=== Expression Visitor Example ===');
// 构建表达式: (2 + 3) * 4
const expr = new MultiplicationExpression(
  new AdditionExpression(
    new NumberExpression(2),
    new NumberExpression(3)
  ),
  new NumberExpression(4)
);

const evaluator = new EvaluatorVisitor();
const result = expr.accept(evaluator);
console.log(\`Expression result: \${result}\`); // 20`,
    demoCode: `// 构建文件系统
const root = new Directory('root');
const file = new File('document.pdf', 1024);
root.addChild(file);

// 使用访问者计算大小
const sizeVisitor = new SizeCalculatorVisitor();
root.accept(sizeVisitor);
console.log(\`Total size: \${sizeVisitor.getTotalSize()} bytes\`);`,
    realWorldExamples: [
      {
        title: '编译器AST处理',
        description: '语法树的不同操作',
        code: `interface ASTNode {
  accept(visitor: ASTVisitor): void;
}

interface ASTVisitor {
  visitVariableDeclaration(node: VariableDeclaration): void;
  visitFunctionCall(node: FunctionCall): void;
  visitBinaryOperation(node: BinaryOperation): void;
}

class CodeGeneratorVisitor implements ASTVisitor {
  visitVariableDeclaration(node: VariableDeclaration): void {
    console.log(\`var \${node.name} = \${node.value};\`);
  }
  
  visitFunctionCall(node: FunctionCall): void {
    console.log(\`\${node.name}(\${node.args.join(', ')});\`);
  }
  
  visitBinaryOperation(node: BinaryOperation): void {
    console.log(\`\${node.left} \${node.operator} \${node.right}\`);
  }
}`
      },
      {
        title: 'DOM元素处理',
        description: 'HTML元素的不同操作',
        code: `interface HTMLElement {
  accept(visitor: HTMLVisitor): void;
}

interface HTMLVisitor {
  visitDiv(element: DivElement): void;
  visitSpan(element: SpanElement): void;
  visitImage(element: ImageElement): void;
}

class SEOAnalyzerVisitor implements HTMLVisitor {
  visitDiv(element: DivElement): void {
    // 分析div结构
  }
  
  visitSpan(element: SpanElement): void {
    // 分析文本内容
  }
  
  visitImage(element: ImageElement): void {
    // 检查alt属性
  }
}`
      }
    ],
    bestPractices: [
      '保持访问者接口稳定',
      '考虑使用抽象访问者基类',
      '注意对象结构的稳定性',
      '合理处理null对象'
    ],
    icon: 'Users'
  },

  // 行为模式 - 解释器
  {
    id: 'interpreter',
    name: '解释器模式',
    category: 'behavioral',
    difficulty: '困难',
    description: '解释器模式给定一个语言，定义它的文法的一种表示，并定义一个解释器，这个解释器使用该表示来解释语言中的句子。',
    principles: [
      '定义语言的文法表示',
      '为文法中的每个规则定义类',
      '使用组合模式构建抽象语法树',
      '解释器遍历语法树执行操作'
    ],
    useCases: [
      '简单脚本语言',
      '配置文件解析',
      '正则表达式',
      'SQL解析器',
      '数学表达式计算'
    ],
    advantages: [
      '易于改变和扩展文法',
      '实现文法比较容易',
      '增加新的解释表达式比较容易',
      '复杂的文法易于维护'
    ],
    disadvantages: [
      '复杂文法难以维护',
      '执行效率较低',
      '可能引起类爆炸',
      '适用场景有限'
    ],
    code: `// 解释器模式示例
// 抽象表达式
interface Expression {
  interpret(context: Context): number;
}

// 上下文类
class Context {
  private variables: Map<string, number> = new Map();
  
  setVariable(name: string, value: number): void {
    this.variables.set(name, value);
  }
  
  getVariable(name: string): number {
    const value = this.variables.get(name);
    if (value === undefined) {
      throw new Error(\`Variable '\${name}' not found\`);
    }
    return value;
  }
  
  hasVariable(name: string): boolean {
    return this.variables.has(name);
  }
}

// 终结符表达式 - 数字
class NumberExpression implements Expression {
  private number: number;
  
  constructor(number: number) {
    this.number = number;
  }
  
  interpret(context: Context): number {
    return this.number;
  }
  
  toString(): string {
    return this.number.toString();
  }
}

// 终结符表达式 - 变量
class VariableExpression implements Expression {
  private name: string;
  
  constructor(name: string) {
    this.name = name;
  }
  
  interpret(context: Context): number {
    return context.getVariable(this.name);
  }
  
  toString(): string {
    return this.name;
  }
}

// 非终结符表达式 - 加法
class AddExpression implements Expression {
  private left: Expression;
  private right: Expression;
  
  constructor(left: Expression, right: Expression) {
    this.left = left;
    this.right = right;
  }
  
  interpret(context: Context): number {
    return this.left.interpret(context) + this.right.interpret(context);
  }
  
  toString(): string {
    return \`(\${this.left.toString()} + \${this.right.toString()})\`;
  }
}

// 非终结符表达式 - 减法
class SubtractExpression implements Expression {
  private left: Expression;
  private right: Expression;
  
  constructor(left: Expression, right: Expression) {
    this.left = left;
    this.right = right;
  }
  
  interpret(context: Context): number {
    return this.left.interpret(context) - this.right.interpret(context);
  }
  
  toString(): string {
    return \`(\${this.left.toString()} - \${this.right.toString()})\`;
  }
}

// 非终结符表达式 - 乘法
class MultiplyExpression implements Expression {
  private left: Expression;
  private right: Expression;
  
  constructor(left: Expression, right: Expression) {
    this.left = left;
    this.right = right;
  }
  
  interpret(context: Context): number {
    return this.left.interpret(context) * this.right.interpret(context);
  }
  
  toString(): string {
    return \`(\${this.left.toString()} * \${this.right.toString()})\`;
  }
}

// 非终结符表达式 - 除法
class DivideExpression implements Expression {
  private left: Expression;
  private right: Expression;
  
  constructor(left: Expression, right: Expression) {
    this.left = left;
    this.right = right;
  }
  
  interpret(context: Context): number {
    const rightValue = this.right.interpret(context);
    if (rightValue === 0) {
      throw new Error('Division by zero');
    }
    return this.left.interpret(context) / rightValue;
  }
  
  toString(): string {
    return \`(\${this.left.toString()} / \${this.right.toString()})\`;
  }
}

// 表达式解析器
class ExpressionParser {
  private tokens: string[];
  private current: number = 0;
  
  constructor(expression: string) {
    // 简单的词法分析 - 按空格分割
    this.tokens = expression.split(/\\s+/).filter(token => token.length > 0);
  }
  
  parse(): Expression {
    const expr = this.parseExpression();
    if (this.current < this.tokens.length) {
      throw new Error(\`Unexpected token: \${this.tokens[this.current]}\`);
    }
    return expr;
  }
  
  private parseExpression(): Expression {
    let left = this.parseTerm();
    
    while (this.current < this.tokens.length) {
      const operator = this.tokens[this.current];
      if (operator === '+') {
        this.current++;
        const right = this.parseTerm();
        left = new AddExpression(left, right);
      } else if (operator === '-') {
        this.current++;
        const right = this.parseTerm();
        left = new SubtractExpression(left, right);
      } else {
        break;
      }
    }
    
    return left;
  }
  
  private parseTerm(): Expression {
    let left = this.parseFactor();
    
    while (this.current < this.tokens.length) {
      const operator = this.tokens[this.current];
      if (operator === '*') {
        this.current++;
        const right = this.parseFactor();
        left = new MultiplyExpression(left, right);
      } else if (operator === '/') {
        this.current++;
        const right = this.parseFactor();
        left = new DivideExpression(left, right);
      } else {
        break;
      }
    }
    
    return left;
  }
  
  private parseFactor(): Expression {
    if (this.current >= this.tokens.length) {
      throw new Error('Unexpected end of expression');
    }
    
    const token = this.tokens[this.current++];
    
    // 括号表达式
    if (token === '(') {
      const expr = this.parseExpression();
      if (this.current >= this.tokens.length || this.tokens[this.current] !== ')') {
        throw new Error('Missing closing parenthesis');
      }
      this.current++;
      return expr;
    }
    
    // 数字
    const number = parseFloat(token);
    if (!isNaN(number)) {
      return new NumberExpression(number);
    }
    
    // 变量
    if (/^[a-zA-Z][a-zA-Z0-9]*$/.test(token)) {
      return new VariableExpression(token);
    }
    
    throw new Error(\`Invalid token: \${token}\`);
  }
}

// 简单的命令解释器
interface Command {
  execute(context: Context): void;
}

class SetCommand implements Command {
  private variable: string;
  private expression: Expression;
  
  constructor(variable: string, expression: Expression) {
    this.variable = variable;
    this.expression = expression;
  }
  
  execute(context: Context): void {
    const value = this.expression.interpret(context);
    context.setVariable(this.variable, value);
    console.log(\`Set \${this.variable} = \${value}\`);
  }
}

class PrintCommand implements Command {
  private expression: Expression;
  
  constructor(expression: Expression) {
    this.expression = expression;
  }
  
  execute(context: Context): void {
    const value = this.expression.interpret(context);
    console.log(\`Result: \${value}\`);
  }
}

class CommandParser {
  static parse(commandStr: string): Command {
    const trimmed = commandStr.trim();
    
    // SET命令: SET x = 5 + 3
    const setMatch = trimmed.match(/^SET\\s+([a-zA-Z][a-zA-Z0-9]*)\\s*=\\s*(.+)$/i);
    if (setMatch) {
      const variable = setMatch[1];
      const expressionStr = setMatch[2];
      const parser = new ExpressionParser(expressionStr);
      const expression = parser.parse();
      return new SetCommand(variable, expression);
    }
    
    // PRINT命令: PRINT x + y
    const printMatch = trimmed.match(/^PRINT\\s+(.+)$/i);
    if (printMatch) {
      const expressionStr = printMatch[1];
      const parser = new ExpressionParser(expressionStr);
      const expression = parser.parse();
      return new PrintCommand(expression);
    }
    
    throw new Error(\`Unknown command: \${commandStr}\`);
  }
}

// 使用示例
console.log('=== Mathematical Expression Interpreter ===');

const context = new Context();

// 设置变量
context.setVariable('x', 10);
context.setVariable('y', 5);

// 解析和执行表达式
const parser1 = new ExpressionParser('x + y * 2');
const expr1 = parser1.parse();
console.log(\`Expression: \${expr1.toString()}\`);
console.log(\`Result: \${expr1.interpret(context)}\`); // 10 + 5 * 2 = 20

const parser2 = new ExpressionParser('( x + y ) * 2');
const expr2 = parser2.parse();
console.log(\`Expression: \${expr2.toString()}\`);
console.log(\`Result: \${expr2.interpret(context)}\`); // (10 + 5) * 2 = 30

console.log('\\n=== Command Interpreter ===');

// 命令解释器示例
const commands = [
  'SET a = 10',
  'SET b = 20',
  'SET c = a + b',
  'PRINT c',
  'PRINT a * b + c'
];

const commandContext = new Context();

commands.forEach(commandStr => {
  console.log(\`Executing: \${commandStr}\`);
  try {
    const command = CommandParser.parse(commandStr);
    command.execute(commandContext);
  } catch (error) {
    console.log(\`Error: \${error.message}\`);
  }
});`,
    demoCode: `const context = new Context();
context.setVariable('x', 10);
context.setVariable('y', 5);

const parser = new ExpressionParser('x + y * 2');
const expression = parser.parse();
console.log(\`Result: \${expression.interpret(context)}\`); // 20`,
    realWorldExamples: [
      {
        title: '配置文件解析器',
        description: '解析简单的配置语法',
        code: `interface ConfigExpression {
  evaluate(): any;
}

class StringLiteral implements ConfigExpression {
  constructor(private value: string) {}
  
  evaluate(): string {
    return this.value;
  }
}

class NumberLiteral implements ConfigExpression {
  constructor(private value: number) {}
  
  evaluate(): number {
    return this.value;
  }
}

class ArrayExpression implements ConfigExpression {
  constructor(private elements: ConfigExpression[]) {}
  
  evaluate(): any[] {
    return this.elements.map(element => element.evaluate());
  }
}`
      },
      {
        title: 'SQL查询解释器',
        description: '简单的SQL语句解析',
        code: `interface SQLExpression {
  execute(database: Database): any[];
}

class SelectExpression implements SQLExpression {
  constructor(
    private columns: string[],
    private table: string,
    private whereClause?: WhereExpression
  ) {}
  
  execute(database: Database): any[] {
    let rows = database.getTable(this.table);
    
    if (this.whereClause) {
      rows = rows.filter(row => this.whereClause!.evaluate(row));
    }
    
    return rows.map(row => {
      const result: any = {};
      this.columns.forEach(col => {
        if (col === '*') {
          Object.assign(result, row);
        } else {
          result[col] = row[col];
        }
      });
      return result;
    });
  }
}`
      }
    ],
    bestPractices: [
      '保持文法简单',
      '使用递归下降解析',
      '考虑使用解析器生成器',
      '提供良好的错误处理'
    ],
    icon: 'Code'
  }
];
